<?php

namespace app\adminapi\controller;

use app\model\PostModel;
use app\model\UsersModel;
use app\model\TopicModel;
use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\Validator as v;
use Webman\Http\Request;

class Post extends BaseAdminApi
{
    protected $dataModel = PostModel::class;
    protected array $with = ['user'];
    protected array $allowSearch = ['title', 'content', 'status', 'user_id'];

    /**
     * 获取帖子详情
     */
    public function getPostDetail(Request $request)
    {
        try {
            $params = v::input($request->get(), [
                'id' => v::stringType()->notEmpty()->setName('帖子ID'),
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        $post = PostModel::with(['user:id,nickname,avatar'])
            ->find($params['id']);

        if (!$post) {
            return $this->fail('帖子不存在');
        }

        return $this->success($post, '获取成功');
    }

    /**
     * 删除帖子
     */
    public function deletePost(Request $request)
    {
        $id = $request->post('id');
        if (empty($id)) {
            return $this->fail('帖子ID不能为空');
        }

        $post = PostModel::find($id);
        if (!$post) {
            return $this->fail('帖子不存在');
        }

        try {
            $post->delete();
            return $this->success('删除成功');
        } catch (\Exception $e) {
            return $this->fail('删除失败：' . $e->getMessage());
        }
    }

    /**
     * 批量删除帖子
     */
    public function batchDeletePosts(Request $request)
    {
        $ids = $request->post('ids');
        if (empty($ids) || !is_array($ids)) {
            return $this->fail('请选择要删除的帖子');
        }

        try {
            // 删除帖子
            PostModel::whereIn('id', $ids)->delete();

            return $this->success('批量删除成功');
        } catch (\Exception $e) {
            return $this->fail('批量删除失败：' . $e->getMessage());
        }
    }
}